//页面一打开,获取所有的学生信息
window.onload = function () {
    const pageno = 1;//默认显示第一页
    const pagenum = 8;//默认一页显示88

    //存储一页多少条,和多少条
    localStorage.setItem("pageno", pageno)
    localStorage.setItem("pagenum", pagenum)

    //渲染学生信息
    rendersutdnet(pageno, pagenum)

    //渲染上面的班级
    const axios = ajax()
    axios({
        url:"/clazz/queryall",
        headers:{token:localStorage.getItem("token")}
    })
    .then(res=>{
        //清空班级
        const clazzInfo = document.getElementById("clazzInfo")
        clazzInfo.innerHTML = "<option value='-1'>请选择</option>"
        //渲染班级
        res.msg.forEach(item=>{
            let str = `
                <option value="${item.cid}">${item.cname}</option>
            `
            clazzInfo.innerHTML += str;
        })
    })
}
/**
 * @Description:  # TODO 分页
 * @Author: 文渊
 * @Date: 2023-09-04 15:44:18
 */
//首页
function pagefirst() {
    const pageno = 1;
    localStorage.setItem("pageno", pageno)
    const pagenum = +localStorage.getItem("pagenum")
    // 发送ajax
    rendersutdnet(pageno, pagenum);
}
//尾页
function pagelast() {
    //将最后一页给计算出来
    const studentcount = +localStorage.getItem("studentcount")
    /* 
        总共17条,一页显示8条
        Math.ceil(17/8)
    */
    const pagenum = +localStorage.getItem("pagenum")
    //计算尾页,根据总条数和一页显示的数据 计算尾页
    const pageno = Math.ceil(studentcount / pagenum);

    localStorage.setItem("pageno", pageno)

    // 发送ajax
    rendersutdnet(pageno, pagenum);
}
//上一页
function pageup() {
    //获取当前页,获取一个显示的条数
    let pageno = +localStorage.getItem("pageno")
    let pagenum = +localStorage.getItem("pagenum")
    pageno--
    localStorage.setItem("pageno",pageno)
    //如果当前页小于第一页,不能请求
    if (pageno < 1) return;
    rendersutdnet(pageno, pagenum)
}
//下一页
function pagedown() {
    //获取当前页,获取一个显示的条数
    let pageno = +localStorage.getItem("pageno")
    let pagenum = +localStorage.getItem("pagenum")
    pageno++
    localStorage.setItem("pageno",pageno)
    //如果当前页大于最后一页,那么也不能请求了
    const studentcount = +localStorage.getItem("studentcount")
    if(pageno > Math.ceil(studentcount / pagenum)) return;

    rendersutdnet(pageno, pagenum)
}
//修改一页显示多少条
const changepagenum = document.getElementById("changepagenum")
changepagenum.addEventListener("change",function(e){
    // console.log(this.value);
    if(this.value == '-1') return;
    //获取value => 一页显示多少条
    let pagenum = this.value;
    localStorage.setItem("pagenum",pagenum)
    //获取当前是第几页
    let pageno = 1;
    localStorage.setItem("pageno",1)
    //调用ajax,渲染
    rendersutdnet(pageno,pagenum)
})

//封装ajax请求,render
function rendersutdnet(pageno, pagenum) {
    const axios = ajax()
    axios({
        url: `/student/queryall?pageno=${pageno}&pagenum=${pagenum}`,
        headers: { token: localStorage.getItem("token") },
    })
        .then(res => {
            //保存一份数据
            localStorage.setItem("studentcount", res.count)
            //渲染操作
            const studentBody = document.getElementById("studentBody")
            studentBody.innerHTML = "";
            res.msg.forEach((item, index) => {
                let str = `
                <tr align="center">
                    <td>${index + 1}</td>    
                    <td>${item.account}</td>    
                    <td>
                        <img width="50px" height="50px" src="${item.url}">
                    </td>    
                    <td>${item.sname}</td>    
                    <td>${item.gender}</td>    
                    <td>${item.age}</td>    
                    <td>${item.email}</td>    
                    <td>${item.cname}</td>    
                    <td>${item.subject}</td>  
                    <td>
                        <button class="btn btn-danger btn-sm" data-id='${item.sid}'>删除</button>
                        <button class="btn btn-warning btn-sm" data-id='${item.sid}' data-bs-toggle="modal" data-bs-target="#studentmodal">修改</button>
                    </td>  
                </tr>
            `
                studentBody.innerHTML += str;
            })
        })
}

/**
 * @Description:  # TODO 删除和修改需要利用时间的委托(事件的委派)
 * @Author: 文渊
 * @Date: 2023-09-05 09:35:23
 */
const studentBody = document.getElementById("studentBody")
studentBody.addEventListener("click",function(e){
    //删除
    if(e.target.className.includes("danger")){
        //防止误删
        const res = confirm("您确定要删除吗?")
        if(res){
            const id = e.target.dataset.id
            //发送ajax
            const axios = ajax()
            axios({
                url:"/student/remove",
                method:"post",
                headers:{token:localStorage.getItem("token")},
                data:{id}
            })
            .then(res=>{
                location.reload();
            })
        }
    }
    //修改
    if(e.target.className.includes("warning")){
        //将模态框的标题变成修改
        localStorage.setItem("tostudentPage","修改")
        //修改模态框的标题
        document.getElementById("studenttitle").innerHTML = "修改"
        //获取id,根据ID发送ajax 请求
        const id = e.target.dataset.id
        //发送ajax
        const axios = ajax()
        axios({
            url:"/student/queryone?id="+id,
            headers:{token:localStorage.getItem("token")}
        })
        .then(res=>{
            document.getElementById("account").value = res.msg[0].account;
            document.getElementById("password").value = res.msg[0].password
            document.getElementById("imgEle").src = res.msg[0].url
            document.getElementById("sname").value = res.msg[0].sname
            document.getElementById("age").value = res.msg[0].age
            document.getElementById("email").value = res.msg[0].email
            document.getElementById("clazzid").value = res.msg[0].clazzid
            document.getElementById("sid").value = res.msg[0].sid
            //继续发送ajax
            axios({
                url:"/clazz/queryall",
                headers:{token:localStorage.getItem("token")}
            })
            .then(result=>{
                //清空班级
                const clazzInfo = document.getElementById("clazzid")
                clazzInfo.innerHTML = "<option value='-1'>请选择</option>"
                //渲染班级
                result.msg.forEach(item=>{
                    let str = `
                        <option value="${item.cid}" ${res.msg[0].clazzid == item.cid ? 'selected' : ''}>${item.cname}</option>
                    `
                    clazzInfo.innerHTML += str;
                })
            })
        })
    }
})


/**
 * @Description:  # TODO 添加或者修改学生信息
 * @Author: 文渊
 * @Date: 2023-09-05 10:24:16
 */
function submitstudent(){
    const title = localStorage.getItem("tostudentPage")
    //收集表单信息
    const account = document.getElementById("account").value.trim()
    const password = document.getElementById("password").value.trim()
    const url = document.getElementById("imgEle").src
    const sname = document.getElementById("sname").value.trim()
    const sex = document.getElementsByClassName("sex")
    let gender = sex[0].checked ? '男' : '女'
    const age = document.getElementById("age").value.trim()
    const email = document.getElementById("email").value.trim()
    const clazzid = document.getElementById("clazzid").value;
    if(clazzid == '-1') return alert("请选择班级")
    // 校验
    if(!(account.length && password.length && sname.length && age.length && email.length)) return window.alert("请输入完整的信息")

    if(title == '添加'){
        //发送ajax
        const axios = ajax()
        axios({
            url:"/student/add",
            method:"post",
            data:{account,password,url,sname,gender,age,email,clazzid},
            headers:{token:localStorage.getItem("token")}
        })
        .then(res=>{
            window.location.reload();
        })
    }else{
        const id = document.getElementById("sid").value;
        console.log(account,password,url,sname,gender,age,email,clazzid,id);
        //发送ajax
        const axios = ajax()
        axios({
            url:"/student/edit",
            method:"post",
            data:{account,password,url,sname,gender,age,email,clazzid,id},
            headers:{token:localStorage.getItem("token")}
        })
        .then(res=>{
            window.location.reload();
        })
    }
}

/**
 * @Description:  # TODO 打开模态框的时候,获取班级信息,用于渲染
 * @Author: 文渊
 * @Date: 2023-09-05 10:39:55
 */
function getClazzInfo(){
    //清空表单信息
    document.getElementById("account").value = ""
    document.getElementById("password").value = ""
    document.getElementById("imgEle").src = "http://s08vr7vdh.hn-bkt.clouddn.com/avatar.png"
    document.getElementById("sname").value = ""
    document.getElementsByClassName("sex")[0].checked = true;
    document.getElementById("age").value = ""
    document.getElementById("email").value = ""
    document.getElementById("clazzid").value = -1;

    //将模特框的标题修改成添加
    localStorage.setItem("tostudentPage","添加")
    //修改模态框的标题
    document.getElementById("studenttitle").innerHTML = "添加"

    const axios = ajax()
    axios({
        url:"/clazz/queryall",
        headers:{token:localStorage.getItem("token")}
    })
    .then(res=>{
        //清空班级
        const clazzInfo = document.getElementById("clazzid")
        clazzInfo.innerHTML = "<option value='-1'>请选择</option>"
        //渲染班级
        res.msg.forEach(item=>{
            let str = `
                <option value="${item.cid}">${item.cname}</option>
            `
            clazzInfo.innerHTML += str;
        })
    })
}


/**
 * @Description:  # TODO 搜索学生
 * @Author: 文渊
 * @Date: 2023-09-05 15:41:33
 */
function searchstudent(){
    const sname = document.getElementById("searchkeywords").value.trim()
    if(!sname.length) return alert("请输入你要搜索的内容")
    //发送ajax
    const axios = ajax()
    axios({
        url:"/student/like?sname="+sname,
        headers:{token:localStorage.getItem("token")}
    })
    .then(res=>{
        //渲染操作
        const studentBody = document.getElementById("studentBody")
        studentBody.innerHTML = "";
        res.msg.forEach((item, index) => {
            let str = `
            <tr align="center">
                <td>${index + 1}</td>    
                <td>${item.account}</td>    
                <td>
                    <img width="50px" height="50px" src="${item.url}">
                </td>    
                <td>${item.sname}</td>    
                <td>${item.gender}</td>    
                <td>${item.age}</td>    
                <td>${item.email}</td>    
                <td>${item.cname}</td>    
                <td>${item.subject}</td>  
                <td>
                    <button class="btn btn-danger btn-sm" data-id='${item.sid}'>删除</button>
                    <button class="btn btn-warning btn-sm" data-id='${item.sid}' data-bs-toggle="modal" data-bs-target="#studentmodal">修改</button>
                </td>  
            </tr>
        `
            studentBody.innerHTML += str;
        })
    })
}

/**
 * @Description:  # TODO 根据班级ID获取班级学生信息
 * @Author: 文渊
 * @Date: 2023-09-05 16:20:50
 */
const clazzInfo = document.getElementById("clazzInfo")
clazzInfo.addEventListener("change",function(e){
    const clazzid = this.value;
    //校验
    if(clazzid == '-1') return window.alert("请选择班级")
    //发送ajax
    const axios = ajax()
    axios({
        url:"/student/querystudent?clazzid="+clazzid,
        headers:{token:localStorage.getItem("token")}
    })
    .then(res=>{
        //渲染操作
        const studentBody = document.getElementById("studentBody")
        studentBody.innerHTML = "";
        res.msg.forEach((item, index) => {
            let str = `
            <tr align="center">
                <td>${index + 1}</td>    
                <td>${item.account}</td>    
                <td>
                    <img width="50px" height="50px" src="${item.url}">
                </td>    
                <td>${item.sname}</td>    
                <td>${item.gender}</td>    
                <td>${item.age}</td>    
                <td>${item.email}</td>    
                <td>${item.cname}</td>    
                <td>${item.subject}</td>  
                <td>
                    <button class="btn btn-danger btn-sm" data-id='${item.sid}'>删除</button>
                    <button class="btn btn-warning btn-sm" data-id='${item.sid}' data-bs-toggle="modal" data-bs-target="#studentmodal">修改</button>
                </td>  
            </tr>
        `
            studentBody.innerHTML += str;
        })
    })
})